package com.ahnu.tongue.service.impl;

import com.ahnu.tongue.common.BusinessException;
import com.ahnu.tongue.config.JwtConfig;
import com.ahnu.tongue.dao.UserMapper;
import com.ahnu.tongue.dto.LoginResponse;
import com.ahnu.tongue.dto.WxLoginRequest;
import com.ahnu.tongue.entity.User;
import com.ahnu.tongue.service.UserService;
import com.ahnu.tongue.utils.WeChatUtils;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final WeChatUtils weChatUtils;
    private final JwtConfig jwtConfig;

    @Override
    @Transactional
    public LoginResponse wxLogin(WxLoginRequest request) {
        // 1. 验证请求参数
        if (request == null || !StringUtils.hasText(request.getCode())) {
            throw new BusinessException("登录code不能为空");
        }

        try {
            // 2. 调用微信接口获取openId
            String openId = weChatUtils.code2Session(request.getCode());
            if (!StringUtils.hasText(openId)) {
                throw new BusinessException("获取openId失败");
            }

            // 3. 查询用户是否存在
            User user = userMapper.findByOpenId(openId);

            // 4. 用户不存在则创建新用户
            if (user == null) {
                user = new User();
                user.setOpenId(openId);
                user.setNickname(StringUtils.hasText(request.getNickname()) ? request.getNickname() : "用户" + openId.substring(0, 8));
                user.setAvatarUrl(request.getAvatarUrl());
                user.setStatus(0);
                userMapper.insert(user);
            }
            // 5. 用户存在则更新信息
            else if (StringUtils.hasText(request.getNickname()) || StringUtils.hasText(request.getAvatarUrl())) {
                if (StringUtils.hasText(request.getNickname())) {
                    user.setNickname(request.getNickname());
                }
                if (StringUtils.hasText(request.getAvatarUrl())) {
                    user.setAvatarUrl(request.getAvatarUrl());
                }
                userMapper.update(user);
            }

            // 6. 生成token
            String token = jwtConfig.generateToken(openId);

            // 7. 构建返回结果
            LoginResponse response = new LoginResponse();
            response.setToken(token);
            
            LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
            BeanUtils.copyProperties(user, userInfo);
            response.setUserInfo(userInfo);

            return response;
        } catch (Exception e) {
            log.error("微信登录失败", e);
            throw new BusinessException("登录失败：" + e.getMessage());
        }
    }

    @Override
    public User getUserById(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }

        User user = userMapper.findById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        return user;
    }

    @Override
    @Transactional
    public void updateUser(User user) {
        if (user == null || user.getId() == null) {
            throw new BusinessException("用户信息不完整");
        }

        User existUser = getUserById(user.getId());
        
        // 只允许更新部分字段
        if (StringUtils.hasText(user.getNickname())) {
            existUser.setNickname(user.getNickname());
        }
        if (StringUtils.hasText(user.getAvatarUrl())) {
            existUser.setAvatarUrl(user.getAvatarUrl());
        }
        if (StringUtils.hasText(user.getPhone())) {
            existUser.setPhone(user.getPhone());
        }
        
        userMapper.update(existUser);
    }

    @Override
    public Long getUserIdFromToken(String token) {
        if (!StringUtils.hasText(token)) {
            throw new BusinessException("token不能为空");
        }

        try {
            String openId = jwtConfig.getOpenIdFromToken(token);
            User user = userMapper.findByOpenId(openId);
            if (user == null) {
                throw new BusinessException("用户不存在");
            }
            return user.getId();
        } catch (ExpiredJwtException e) {
            throw new BusinessException("token已过期，请重新登录");
        } catch (Exception e) {
            throw new BusinessException("无效的token");
        }
    }
} 